﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Text;
using xiushen.Domain;
using xiushen.Infrastructure;

namespace ImageUploader
{
    class Program
    {
        private static readonly AdminRepository repository = new AdminRepository();
        static void Main(string[] args)
        {
            FileUpload();
        }
        static void FileUpload()
        {

            var path = ConfigurationManager.AppSettings["UploadSourceFile"];
            var destinationFolder = ConfigurationManager.AppSettings["UpLoadFile"];
            var files = Directory.GetFiles(path);
            var folername = Path.GetFileName(path);
            var id = repository.QueryAll<Category>().Where(r => r.Name == folername).FirstOrDefault().ID.ToString();
            foreach (var file in files)
            {
                 string filePath = string.Empty;
                var attachment = new Attachment();
                var extension = Path.GetExtension(file);
                var type = extension == ".pdf" ? Constants.Book : Constants.Image;
                filePath = CreateFolder(id, destinationFolder, type);
                var fileName = String.Format("{0}.{1}", Guid.NewGuid().ToString(), extension);
                filePath = Path.Combine(filePath, fileName);
                attachment.FileName = fileName;
                attachment.FileType = type;
                File.Copy(file,filePath);
                attachment.UploadTime = DateTime.Now;
                attachment.UploadUserName = "Tool";
                repository.SaveAttachMent(attachment);
            }
        }
        private static  string CreateFolder(string categoryId, string folderPath, string type)
        {

            folderPath = Path.Combine(folderPath, type);
            var path = Path.Combine(folderPath, categoryId);
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            return path;
        }

    }
    
}
